import pygame
import sys
import copy
from pygame.locals import *
import random
import time
from game_rules import *  # 导入围棋规则函数
import ai
import threading

# 初始化
pygame.init()


# 添加稳健的中文字体支持
def get_chinese_font():
    """安全地获取中文字体，避免所有可能的异常"""
    try:
        pygame.font.init()

        # 尝试系统字体
        chinese_fonts = [
            "Microsoft YaHei", "SimHei", "KaiTi", "STXihei",
            "STKaiti", "STSong", "STFangsong", "FangSong",
            "SimSun", "Arial Unicode MS", "Hei", "PingFang SC",
            "Hiragino Sans GB", "WenQuanYi Micro Hei"
        ]

        available_fonts = pygame.font.get_fonts()
        for font_name in chinese_fonts:
            if any(f.lower() == font_name.lower() for f in available_fonts):
                return font_name

        # 尝试文件字体
        font_files = [
            "simhei.ttf", "msyh.ttf", "simsun.ttc",
            "STKAITI.TTF", "simfang.ttf", "simyou.ttf"
        ]

        for font_file in font_files:
            try:
                # 尝试加载字体文件
                test_font = pygame.font.Font(font_file, 16)
                test_surface = test_font.render("测试", True, (0, 0, 0))
                # 验证字体是否可以渲染中文
                if test_surface.get_width() > 0:
                    return font_file
            except:
                continue

        # 最终回退方案
        print("警告：未能找到中文字体，使用默认字体")
        return None
    except Exception as e:
        print(f"字体初始化错误: {e}")
        return None


# 安全加载字体
CHINESE_FONT = get_chinese_font()


# 字体创建增加容错机制
def create_font(size):
    """创建字体，带有错误处理"""
    try:
        if CHINESE_FONT:
            # 如果是文件路径
            if CHINESE_FONT.endswith('.ttf') or CHINESE_FONT.endswith('.ttc'):
                return pygame.font.Font(CHINESE_FONT, size)
            # 如果是系统字体
            return pygame.font.SysFont(CHINESE_FONT, size)
        return pygame.font.SysFont(None, size)
    except:
        try:
            return pygame.font.SysFont("", size)
        except:
            # 最终回退方案
            return pygame.font.SysFont(None, size)


# 安全创建所有字体
FONT_CHINESE = create_font(20)
FONT_TITLE = create_font(26)
FONT_RESULT = create_font(32)
FONT_START_TITLE = create_font(48)
FONT_START_BUTTON = create_font(36)

# 常量定义
BOARD_SIZES = [5, 9, 13, 19]
COLORS = {
    'BACKGROUND': (240, 217, 181),
    'BOARD': (222, 184, 135),
    'BLACK': (0, 0, 0),
    'WHITE': (255, 255, 255),
    'HIGHLIGHT': (255, 0, 0),
    'BUTTON': (180, 160, 120),
    'BUTTON_HOVER': (200, 180, 140),
    'TEXT': (50, 50, 50),
    'MENU': (230, 220, 200),
    'MENU_HOVER': (210, 200, 180),
    'TERRITORY_BLACK': (100, 100, 255, 100),  # 半透明的蓝色表示黑方领地
    'TERRITORY_WHITE': (255, 100, 100, 100),  # 半透明的红色表示白方领地
    'MODAL_BG': (250, 240, 230),  # 弹窗背景色
    'MODAL_BORDER': (150, 120, 100),  # 弹窗边框色
    'START_BG': (196, 175, 147),  # 开始界面背景色
    'START_BUTTON': (150, 135, 115),  # 开始界面按钮
    'START_BUTTON_HOVER': (180, 160, 140),  # 开始界面按钮悬停
    'START_TEXT': (60, 50, 40),  # 开始界面文本颜色
    'HINT_BLACK': (0, 0, 0, 80),  # 半透明的黑色落点提示
    'HINT_WHITE': (255, 255, 255, 80),  # 半透明的白色落点提示
}


class StartMenu:
    """开始菜单类"""

    def __init__(self):
        # 窗口设置
        self.window_width = 1000
        self.window_height = 800
        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        pygame.display.set_caption("围棋游戏 - 开始菜单")

        # 按钮设置 - 保留人机对弈按钮，增加退出按钮
        self.ai_button = pygame.Rect(
            (self.window_width - 300) // 2,
            self.window_height // 2 + 50,
            300, 60
        )

        # 添加退出按钮
        self.exit_button = pygame.Rect(
            (self.window_width - 300) // 2,
            self.window_height // 2 + 130,
            300, 60
        )

        self.running = True
        self.selected_mode = None  # 记录用户选择的模式

    def draw(self):
        """绘制开始菜单"""
        # 绘制背景
        self.screen.fill(COLORS['START_BG'])

        # 绘制标题
        title_surf = FONT_START_TITLE.render("围棋游戏", True, COLORS['START_TEXT'])
        title_rect = title_surf.get_rect(center=(self.window_width // 2, self.window_height // 3))
        self.screen.blit(title_surf, title_rect)

        # 绘制按钮 - 人机对弈和退出按钮
        self._draw_button(self.ai_button, "人机对弈")
        self._draw_button(self.exit_button, "退出游戏")

        pygame.display.flip()

    def _draw_button(self, rect, text):
        """绘制单个按钮"""
        # 检测鼠标是否悬停在按钮上
        mouse_pos = pygame.mouse.get_pos()
        is_hovered = rect.collidepoint(mouse_pos)

        # 绘制按钮背景
        bg_color = COLORS['START_BUTTON_HOVER'] if is_hovered else COLORS['START_BUTTON']
        pygame.draw.rect(self.screen, bg_color, rect, border_radius=10)
        pygame.draw.rect(self.screen, COLORS['MODAL_BORDER'], rect, 3, border_radius=10)

        # 绘制按钮文本
        text_surf = FONT_START_BUTTON.render(text, True, COLORS['START_TEXT'])
        text_rect = text_surf.get_rect(center=rect.center)
        self.screen.blit(text_surf, text_rect)

    def handle_events(self):
        """处理事件"""
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == MOUSEBUTTONDOWN:
                if self.ai_button.collidepoint(event.pos):
                    self.selected_mode = 'ai'
                    self.running = False
                elif self.exit_button.collidepoint(event.pos):
                    pygame.quit()
                    sys.exit()

    def run(self):
        """运行开始菜单循环"""
        while self.running:
            self.handle_events()
            self.draw()
        return self.selected_mode


class GoGame:
    def __init__(self, size=19):
        # 游戏状态 - 固定为人机对弈模式
        self.mode = 'ai'
        self.board_size = size
        self.board = [[None] * size for _ in range(size)]
        self.player_side = 'BLACK'  # 玩家选择的棋子颜色
        self.ai_side = 'WHITE'  # AI棋子颜色
        self.current_player = 'BLACK'  # 默认为黑棋先行
        self.captures = {'BLACK': 0, 'WHITE': 0}
        self.game_over = False
        self.selected_size = size
        self.last_move = None  # 记录上一步落子位置
        self.consecutive_pass = 0  # 记录连续pass的次数
        self.territory = [[None] * size for _ in range(size)]  # 记录领地归属
        self.black_score = 0
        self.white_score = 0
        self.winner = None
        self.return_to_menu = False  # 标记是否要返回菜单
        self.position_history = []  # 记录历史局面
        self.hover_pos = None  # 鼠标悬停位置
        self.side_menu_open = False  # 棋子选择菜单是否打开
        self.ai_thread = None  # 添加AI线程变量
        self.ai_move_in_progress = False  # 添加AI移动标志
        self.last_ai_pass = False  # 记录AI是否pass

        # 窗口设置
        self.window_width = 1000
        self.window_height = 800
        self.board_width = int(self.window_width * 0.7)
        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        pygame.display.set_caption("围棋游戏")

        # 菜单设置
        self.menu_bar_rect = pygame.Rect(0, 0, self.window_width, 30)
        self.game_menu_rect = pygame.Rect(10, 5, 60, 20)
        self.game_menu_open = False
        self.size_menu_open = False
        self.menu_interaction_blocked = False

        # 难度选择设置（始终可见）
        self.difficulty = '5k'  # 默认难度
        self.difficulty_menu_open = False
        # 扩展为完整的围棋等级体系
        self.difficulty_options = [
            {'text': '25k', 'rect': None, 'level': '25k'},
            {'text': '15k', 'rect': None, 'level': '15k'},
            {'text': '10k', 'rect': None, 'level': '10k'},
            {'text': '5k', 'rect': None, 'level': '5k'},
            {'text': '2k', 'rect': None, 'level': '2k'},
            {'text': '1k', 'rect': None, 'level': '1k'},
            {'text': '1d', 'rect': None, 'level': '1d'},
            {'text': '2d', 'rect': None, 'level': '2d'},
            {'text': '3d', 'rect': None, 'level': '3d'},
            {'text': '4d', 'rect': None, 'level': '4d'},
            {'text': '5d', 'rect': None, 'level': '5d'},
            {'text': '6d', 'rect': None, 'level': '6d'},
            {'text': '7d', 'rect': None, 'level': '7d'},
            {'text': '8d', 'rect': None, 'level': '8d'},
            {'text': '1p', 'rect': None, 'level': '1p'}
        ]

        # 游戏菜单项 (修改：添加选择棋子选项)
        self.menu_items = [
            {'text': '新游戏', 'rect': pygame.Rect(10, 35, 120, 25), 'action': 'new_game'},
            {'text': '棋盘大小', 'rect': pygame.Rect(10, 65, 120, 25), 'action': 'size_menu'},
            {'text': '难度选择', 'rect': pygame.Rect(10, 95, 120, 25), 'action': 'difficulty_menu'},
            {'text': '选择棋子', 'rect': pygame.Rect(10, 125, 120, 25), 'action': 'choose_side'},  # 新增选项
            {'text': '返回首页', 'rect': pygame.Rect(10, 155, 120, 25), 'action': 'return_home'},
            {'text': '退出', 'rect': pygame.Rect(10, 185, 120, 25), 'action': 'exit'}
        ]

        # 棋盘尺寸选项
        self.size_options = [
            {'text': '5x5', 'rect': pygame.Rect(135, 65, 80, 25), 'size': 5},
            {'text': '9x9', 'rect': pygame.Rect(135, 95, 80, 25), 'size': 9},
            {'text': '13x13', 'rect': pygame.Rect(135, 125, 80, 25), 'size': 13},
            {'text': '19x19', 'rect': pygame.Rect(135, 155, 80, 25), 'size': 19}
        ]

        # 棋子选择选项 (新增子菜单)
        self.side_options = [
            {'text': '黑棋', 'rect': pygame.Rect(135, 125, 80, 25), 'side': 'BLACK', 'order': '先手'},
            {'text': '白棋', 'rect': pygame.Rect(135, 155, 80, 25), 'side': 'WHITE', 'order': '后手'}
        ]

        # 右侧面板
        panel_width = self.window_width - self.board_width
        self.info_panel_rect = pygame.Rect(self.board_width, 0, panel_width, self.window_height)

        # 游戏信息区域
        self.game_info_rect = pygame.Rect(self.board_width + 10, 40, panel_width - 20, 260)

        # 选项面板
        self.option_panel_rect = pygame.Rect(self.board_width + 10, self.window_height - 180 - 30,
                                             panel_width - 20, 150)

        # 按钮
        button_width = panel_width - 40
        self.buttons = [
            {'text': '悔棋', 'rect': pygame.Rect(self.board_width + 20,
                                                 self.window_height - 170 - 30,
                                                 button_width, 35),
             'action': 'withdraw'},
            {'text': '认输', 'rect': pygame.Rect(self.board_width + 20,
                                                 self.window_height - 125 - 30,
                                                 button_width, 35),
             'action': 'admit_defeat'},
            {'text': '停着', 'rect': pygame.Rect(self.board_width + 20,
                                                 self.window_height - 80 - 30,
                                                 button_width, 35),
             'action': 'pass_turn'}
        ]

    def new_game(self):
        """开始新游戏"""
        self.board = [[None] * self.board_size for _ in range(self.board_size)]
        self.territory = [[None] * self.board_size for _ in range(self.board_size)]
        self.current_player = self.player_side if self.player_side == 'BLACK' else self.ai_side
        self.captures = {'BLACK': 0, 'WHITE': 0}
        self.game_over = False
        self.last_move = None
        self.consecutive_pass = 0
        self.black_score = 0
        self.white_score = 0
        self.winner = None
        self.game_menu_open = False
        self.size_menu_open = False
        self.side_menu_open = False
        self.menu_interaction_blocked = False
        self.position_history = []  # 清空历史记录
        self.hover_pos = None  # 重置悬停位置

        # 如果玩家选择白棋（后手），让AI先手落子
        if self.player_side == 'WHITE' and self.current_player == self.ai_side:
            pygame.time.delay(200)  # 添加短暂延迟让界面更新
            self.ai_move()

    def switch_player(self):
        """切换玩家角色（黑棋/白棋）并重置游戏"""
        # 交换玩家和AI的棋子颜色
        self.player_side = 'WHITE' if self.player_side == 'BLACK' else 'BLACK'
        self.ai_side = 'WHITE' if self.player_side == 'BLACK' else 'BLACK'

        # 重置当前玩家
        self.current_player = 'BLACK'

        # 开始新游戏
        self.new_game()


    # 在GoGame类中修改place_stone方法
    def place_stone(self, row, col, is_ai=False):
        """在指定位置放置棋子，使用规则函数"""
        if self.game_over:
            return False

        # 如果是AI落子，跳过玩家回合检查
        if not is_ai:
            # 检查是否是当前玩家回合
            if self.current_player != self.player_side:
                return False

        if 0 <= row < self.board_size and 0 <= col < self.board_size and not self.board[row][col]:
            # 使用规则函数尝试落子
            new_board, new_captures, success = place_stone(
                self.board,
                self.current_player,
                row,
                col,
                self.board_size,
                self.position_history
            )

            if success:
                # 更新棋盘和捕获信息
                self.board = new_board
                # 合并捕获计数
                for color in self.captures:
                    self.captures[color] += new_captures[color]

                # 重置连续pass计数
                self.consecutive_pass = 0

                # 保存当前状态到历史记录
                self.position_history.append(copy.deepcopy(self.board))
                if len(self.position_history) > 10:
                    self.position_history.pop(0)

                self.last_move = (row, col)

                # 切换玩家
                self.current_player = 'WHITE' if self.current_player == 'BLACK' else 'BLACK'

                # 如果轮到AI下棋，启动AI线程
                if not self.game_over and self.current_player == self.ai_side and not self.ai_move_in_progress:
                    # 创建并启动AI线程
                    self.ai_move_in_progress = True
                    self.ai_thread = threading.Thread(target=self.ai_move)
                    self.ai_thread.daemon = True  # 设置为守护线程
                    self.ai_thread.start()

                return True
        return False

    def ai_move(self):
        """AI下棋，调用ai模块"""
        # 计算当前步数（棋盘上已有棋子的数量）
        move_count = sum(1 for row in self.board for cell in row if cell is not None)

        # 调用AI模块获取落子位置
        move = ai.get_ai_move(
            self.board,
            self.board_size,
            self.current_player,
            self.difficulty,
            self.position_history,
            move_count
        )

        # 处理AI投降
        if move == "SURRENDER":
            self.admit_defeat()
            self.last_ai_pass = True
            return

        if move is None:  # pass
            self.pass_turn()
            # 添加显示"电脑选择pass"的逻辑
            self.last_ai_pass = True
        elif move == (None, None):  # 特殊处理低级AI
            self.pass_turn()
            # 添加显示"电脑选择pass"的逻辑
            self.last_ai_pass = True
        else:
            row, col = move
            self.place_stone(int(row), int(col), is_ai=True)
            self.last_ai_pass = False

        # AI移动完成后重置标志
        self.ai_move_in_progress = False

    def withdraw(self):
        """悔棋功能"""
        if not self.position_history:
            return

        # 获取上一个状态
        self.board = copy.deepcopy(self.position_history.pop())

        # 切换玩家
        self.current_player = 'WHITE' if self.current_player == 'BLACK' else 'BLACK'

        # 重置游戏结束状态
        if self.game_over:
            self.game_over = False
            self.winner = None

        # 如果游戏重置后轮到AI，让AI走棋
        if not self.game_over and self.current_player == self.ai_side:
            self.ai_move()

    def admit_defeat(self):
        """认输"""
        if self.game_over:
            return

        self.game_over = True
        self.winner = 'WHITE' if self.current_player == 'BLACK' else 'BLACK'
        self.calculate_score()

    def pass_turn(self):
        """停着"""
        if self.game_over:
            return

        self.current_player = 'WHITE' if self.current_player == 'BLACK' else 'BLACK'
        self.last_move = None
        self.consecutive_pass += 1  # 增加pass计数

        # 检查是否连续两次pass
        if self.consecutive_pass >= 2:
            self.calculate_score()  # 计算得分
            self.game_over = True

        # 如果轮到AI下棋
        if not self.game_over and self.current_player == self.ai_side:
            self.ai_move()

    def calculate_score(self):
        """使用规则函数计算得分"""
        # 标记领地
        self.territory = mark_territory(self.board, self.board_size)

        # 计算得分 - 修复参数传递问题
        self.black_score, self.white_score, winner_str = calculate_score(
            board=self.board,
            territory=self.territory,
            captures=self.captures
        )

        # 设置胜者
        if "黑方胜" in winner_str:
            self.winner = "黑方胜"
        elif "白方胜" in winner_str:
            self.winner = "白方胜"
        else:
            self.winner = "平局"

    def is_board_interaction_allowed(self):
        """检查是否允许棋盘交互"""
        return not (
                    self.game_menu_open or self.size_menu_open or self.side_menu_open or self.game_over or self.menu_interaction_blocked)

    def draw(self):
        """绘制整个游戏界面"""
        self.screen.fill(COLORS['BACKGROUND'])
        # 绘制棋盘
        self.draw_board()
        # 绘制菜单栏
        pygame.draw.rect(self.screen, COLORS['MENU'], self.menu_bar_rect)
        pygame.draw.rect(self.screen, COLORS['MENU_HOVER'] if self.game_menu_rect.collidepoint(pygame.mouse.get_pos())
        else COLORS['MENU'], self.game_menu_rect)

        # 使用中文字体渲染文本
        text = FONT_CHINESE.render("游戏", True, COLORS['TEXT'])
        self.screen.blit(text, (self.game_menu_rect.x + 15, self.game_menu_rect.y + 3))

        # 绘制菜单
        if self.game_menu_open:
            for item in self.menu_items:
                pygame.draw.rect(self.screen, COLORS['MENU_HOVER'] if item['rect'].collidepoint(pygame.mouse.get_pos())
                else COLORS['MENU'], item['rect'])
                text = FONT_CHINESE.render(item['text'], True, COLORS['TEXT'])
                self.screen.blit(text, (item['rect'].x + 10, item['rect'].y + 5))

            # 绘制棋盘大小菜单
            if self.size_menu_open:
                for option in self.size_options:
                    pygame.draw.rect(self.screen,
                                     COLORS['MENU_HOVER'] if option['rect'].collidepoint(pygame.mouse.get_pos())
                                     else COLORS['MENU'], option['rect'])
                    text = FONT_CHINESE.render(option['text'], True, COLORS['TEXT'])
                    self.screen.blit(text, (option['rect'].x + 10, option['rect'].y + 5))

            # 绘制棋子选择菜单 (新增)
            if self.side_menu_open:
                for option in self.side_options:
                    pygame.draw.rect(self.screen,
                                     COLORS['MENU_HOVER'] if option['rect'].collidepoint(pygame.mouse.get_pos())
                                     else COLORS['MENU'], option['rect'])
                    text = FONT_CHINESE.render(option['text'], True, COLORS['TEXT'])
                    self.screen.blit(text, (option['rect'].x + 10, option['rect'].y + 5))

            # 绘制难度选择菜单 - 改为两列显示
            if self.difficulty_menu_open:
                # 第一列 (从65开始)
                for i, option in enumerate(self.difficulty_options[:8]):
                    option_rect = pygame.Rect(135, 65 + i * 25, 80, 25)
                    # 更新选项的位置以便点击
                    option['rect'] = option_rect

                    # 高亮当前选择的难度
                    if option['level'] == self.difficulty:
                        pygame.draw.rect(self.screen, COLORS['HIGHLIGHT'], option_rect)

                    # 绘制选项背景
                    pygame.draw.rect(self.screen,
                                     COLORS['MENU_HOVER'] if option_rect.collidepoint(pygame.mouse.get_pos())
                                     else COLORS['MENU'], option_rect)
                    pygame.draw.rect(self.screen, COLORS['BLACK'], option_rect, 1)

                    # 绘制文本
                    text = FONT_CHINESE.render(option['text'], True, COLORS['TEXT'])
                    self.screen.blit(text, (option_rect.x + 10, option_rect.y + 5))

                # 第二列
                for i, option in enumerate(self.difficulty_options[8:]):
                    option_rect = pygame.Rect(135 + 100, 65 + i * 25, 80, 25)
                    option['rect'] = option_rect

                    if option['level'] == self.difficulty:
                        pygame.draw.rect(self.screen, COLORS['HIGHLIGHT'], option_rect)

                    pygame.draw.rect(self.screen,
                                     COLORS['MENU_HOVER'] if option_rect.collidepoint(pygame.mouse.get_pos())
                                     else COLORS['MENU'], option_rect)
                    pygame.draw.rect(self.screen, COLORS['BLACK'], option_rect, 1)

                    text = FONT_CHINESE.render(option['text'], True, COLORS['TEXT'])
                    self.screen.blit(text, (option_rect.x + 10, option_rect.y + 5))

        # 绘制右侧面板
        pygame.draw.rect(self.screen, COLORS['MENU'], self.info_panel_rect)

        # 游戏信息区域
        pygame.draw.rect(self.screen, COLORS['BACKGROUND'], self.game_info_rect)
        pygame.draw.rect(self.screen, COLORS['BLACK'], self.game_info_rect, 2)

        title = FONT_TITLE.render("游戏信息", True, COLORS['TEXT'])
        self.screen.blit(title, (self.game_info_rect.x + 10, self.game_info_rect.y + 10))

        # 显示玩家棋子信息 (新增)
        player_side_text = FONT_TITLE.render(f"玩家: {'黑棋' if self.player_side == 'BLACK' else '白棋'}", True,
                                             COLORS['TEXT'])
        self.screen.blit(player_side_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 40))

        player_order_text = FONT_TITLE.render(f"回合: {'先手' if self.player_side == 'BLACK' else '后手'}", True,
                                              COLORS['TEXT'])
        self.screen.blit(player_order_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 65))

        label = FONT_TITLE.render("当前玩家:", True, COLORS['TEXT'])
        self.screen.blit(label, (self.game_info_rect.x + 20, self.game_info_rect.y + 90))

        # 绘制棋子图标
        stone_radius = 12
        stone_x = self.game_info_rect.x + 150  # 文字右侧位置
        stone_y = self.game_info_rect.y + 90 + stone_radius

        if self.current_player == 'BLACK':
            pygame.draw.circle(self.screen, COLORS['BLACK'], (stone_x, stone_y), stone_radius)
        else:
            pygame.draw.circle(self.screen, COLORS['WHITE'], (stone_x, stone_y), stone_radius)
            pygame.draw.circle(self.screen, COLORS['BLACK'], (stone_x, stone_y), stone_radius, 1)  # 白棋描边

        capture_text = FONT_TITLE.render(f"黑子提子: {self.captures['BLACK']}",
                                         True, COLORS['TEXT'])
        self.screen.blit(capture_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 115))

        capture_text = FONT_TITLE.render(f"白子提子: {self.captures['WHITE']}",
                                         True, COLORS['TEXT'])
        self.screen.blit(capture_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 140))

        # 显示游戏模式
        mode_text = FONT_TITLE.render(f"模式: 人机对弈",
                                      True, COLORS['TEXT'])
        self.screen.blit(mode_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 165))

        # 显示难度
        diff_text = FONT_TITLE.render(f"难度: {self.difficulty}",
                                      True, COLORS['TEXT'])
        self.screen.blit(diff_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 190))

        # 显示游戏结果
        if self.game_over and self.winner:
            # 在游戏信息区域显示结果
            result_text = FONT_RESULT.render(f"游戏结束", True, COLORS['TEXT'])
            self.screen.blit(result_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 215))

            winner_text = FONT_RESULT.render(f"胜方: {self.winner}", True, COLORS['TEXT'])
            self.screen.blit(winner_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 245))

            black_score_text = FONT_TITLE.render(f"黑方得分: {self.black_score:.1f}", True, COLORS['TEXT'])
            self.screen.blit(black_score_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 275))

            white_score_text = FONT_TITLE.render(f"白方得分: {self.white_score:.1f}", True, COLORS['TEXT'])
            self.screen.blit(white_score_text, (self.game_info_rect.x + 20, self.game_info_rect.y + 300))

            # 在游戏信息区域下方显示"电脑正在思考..."
        if self.ai_move_in_progress and not self.game_over:
            # 计算提示文本的位置（游戏信息区域下方）
            thinking_text = FONT_CHINESE.render("电脑正在思考...", True, COLORS['TEXT'])
            text_x = self.game_info_rect.centerx - thinking_text.get_width() // 2
            text_y = self.game_info_rect.bottom + 20  # 在游戏信息区域下方20像素处
            self.screen.blit(thinking_text, (text_x, text_y))
        # 选项区域
        pygame.draw.rect(self.screen, COLORS['BACKGROUND'], self.option_panel_rect)
        pygame.draw.rect(self.screen, COLORS['BLACK'], self.option_panel_rect, 2)

        option_title = FONT_TITLE.render("操作选项", True, COLORS['TEXT'])
        self.screen.blit(option_title, (self.option_panel_rect.x + 10, self.option_panel_rect.y + 10))

        # 绘制按钮
        for button in self.buttons:
            pygame.draw.rect(self.screen, COLORS['BUTTON_HOVER'] if button['rect'].collidepoint(pygame.mouse.get_pos())
            else COLORS['BUTTON'], button['rect'])
            pygame.draw.rect(self.screen, COLORS['BLACK'], button['rect'], 1)
            text = FONT_CHINESE.render(button['text'], True, COLORS['TEXT'])
            self.screen.blit(text, (button['rect'].x + 10, button['rect'].y + 8))

        pygame.display.flip()

    def draw_board(self):
        """绘制围棋棋盘"""
        board_rect = pygame.Rect(50, 50, self.board_width - 100, self.board_width - 100)

        # 添加棋盘禁用状态的视觉反馈
        if not self.is_board_interaction_allowed():
            # 创建半透明表面
            overlay = pygame.Surface((board_rect.width, board_rect.height), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 100))  # 半透明黑色
            pygame.draw.rect(self.screen, COLORS['BOARD'], board_rect)
            self.screen.blit(overlay, (board_rect.x, board_rect.y))
        else:
            pygame.draw.rect(self.screen, COLORS['BOARD'], board_rect)

        # 计算格子大小
        cell_size = min(board_rect.width, board_rect.height) / (self.board_size - 1)

        # 绘制网格线
        for i in range(self.board_size):
            # 横线
            pygame.draw.line(self.screen, COLORS['BLACK'],
                             (board_rect.left, board_rect.top + i * cell_size),
                             (board_rect.right, board_rect.top + i * cell_size), 1)
            # 竖线
            pygame.draw.line(self.screen, COLORS['BLACK'],
                             (board_rect.left + i * cell_size, board_rect.top),
                             (board_rect.left + i * cell_size, board_rect.bottom), 1)

        # 绘制星位（天元和星）
        star_points = []
        if self.board_size >= 13:
            star_points = [3, self.board_size // 2, self.board_size - 4]
        elif self.board_size >= 9:
            star_points = [2, self.board_size // 2, self.board_size - 3]
        else:
            star_points = [self.board_size // 2]

        for x in star_points:
            for y in star_points:
                pygame.draw.circle(self.screen, COLORS['BLACK'],
                                   (int(board_rect.left + x * cell_size),
                                    int(board_rect.top + y * cell_size)), 4)

        # 在游戏结束时绘制领地标记
        if self.game_over:
            for r in range(self.board_size):
                for c in range(self.board_size):
                    if self.territory[r][c] == 'BLACK':
                        x = int(board_rect.left + c * cell_size)
                        y = int(board_rect.top + r * cell_size)
                        s = pygame.Surface((int(cell_size), int(cell_size)), pygame.SRCALPHA)
                        s.fill(COLORS['TERRITORY_BLACK'])
                        self.screen.blit(s, (x - int(cell_size / 2), y - int(cell_size / 2)))
                    elif self.territory[r][c] == 'WHITE':
                        x = int(board_rect.left + c * cell_size)
                        y = int(board_rect.top + r * cell_size)
                        s = pygame.Surface((int(cell_size), int(cell_size)), pygame.SRCALPHA)
                        s.fill(COLORS['TERRITORY_WHITE'])
                        self.screen.blit(s, (x - int(cell_size / 2), y - int(cell_size / 2)))

        # 绘制棋子
        for row in range(self.board_size):
            for col in range(self.board_size):
                if self.board[row][col]:
                    stone_color = COLORS['BLACK'] if self.board[row][col] == 'BLACK' else COLORS['WHITE']
                    pygame.draw.circle(self.screen, stone_color,
                                       (int(board_rect.left + col * cell_size),
                                        int(board_rect.top + row * cell_size)),
                                       int(cell_size * 0.4))
                    if stone_color == COLORS['WHITE']:
                        pygame.draw.circle(self.screen, COLORS['BLACK'],
                                           (int(board_rect.left + col * cell_size),
                                            int(board_rect.top + row * cell_size)),
                                           int(cell_size * 0.4), 1)

        # 标记AI的最后落子位置
        if self.last_move and self.current_player == self.player_side:
            # 只有当上一步是AI落子时才标记
            row, col = self.last_move
            x = int(board_rect.left + col * cell_size)
            y = int(board_rect.top + row * cell_size)

            # 绘制红色方框
            stone_radius = int(cell_size * 0.4)  # 棋子半径
            rect_size = stone_radius * 2 + 4  # 方框大小，比棋子直径稍大一点
            rect = pygame.Rect(
                x - stone_radius - 2,  # 向左偏移半径+2像素
                y - stone_radius - 2,  # 向上偏移半径+2像素
                rect_size,
                rect_size
            )
            pygame.draw.rect(self.screen, COLORS['HIGHLIGHT'], rect, 2)

        # 绘制落点提示（仅在允许落子时显示）
        if (self.is_board_interaction_allowed() and
                not self.game_over and
                self.current_player == self.player_side and
                self.hover_pos):

            row, col = self.hover_pos
            # 确保位置在棋盘范围内且没有棋子
            if (0 <= row < self.board_size and
                    0 <= col < self.board_size and
                    not self.board[row][col]):
                # 选择当前玩家对应的提示颜色
                hint_color = COLORS['HINT_BLACK'] if self.current_player == 'BLACK' else COLORS['HINT_WHITE']

                # 计算落点位置
                x = int(board_rect.left + col * cell_size)
                y = int(board_rect.top + row * cell_size)

                # 创建半透明表面
                hint_surface = pygame.Surface((int(cell_size * 0.8), int(cell_size * 0.8)), pygame.SRCALPHA)
                pygame.draw.circle(
                    hint_surface,
                    hint_color,
                    (int(cell_size * 0.4), int(cell_size * 0.4)),
                    int(cell_size * 0.25)
                )

                # 绘制提示
                self.screen.blit(
                    hint_surface,
                    (x - int(cell_size * 0.4), y - int(cell_size * 0.4))
                )

        # 在棋盘下方显示"电脑选择pass"
        if self.last_ai_pass and not self.game_over:
                board_rect = pygame.Rect(50, 50, self.board_width - 100, self.board_width - 100)
                text = FONT_CHINESE.render("电脑选择pass", True, COLORS['TEXT'])
                text_x = board_rect.centerx - text.get_width() // 2
                text_y = board_rect.bottom + 20
                self.screen.blit(text, (text_x, text_y))

    def run(self):
        """运行游戏主循环"""
        clock = pygame.time.Clock()

        while True:
            # 更新悬停位置
            self.hover_pos = None

            # 检查是否允许落子
            if (self.is_board_interaction_allowed() and
                    not self.game_over and
                    self.current_player == self.player_side):

                mouse_pos = pygame.mouse.get_pos()
                board_rect = pygame.Rect(50, 50, self.board_width - 100, self.board_width - 100)

                if board_rect.collidepoint(mouse_pos):
                    cell_size = min(board_rect.width, board_rect.height) / (self.board_size - 1)
                    col = round((mouse_pos[0] - board_rect.left) / cell_size)
                    row = round((mouse_pos[1] - board_rect.top) / cell_size)
                    self.hover_pos = (int(row), int(col))

            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()

                    # 重置菜单交互状态
                    self.menu_interaction_blocked = False

                    # 检查菜单点击
                    if self.game_menu_rect.collidepoint(mouse_pos):
                        self.game_menu_open = not self.game_menu_open
                        self.size_menu_open = False
                        self.side_menu_open = False
                        self.difficulty_menu_open = False
                    elif self.game_menu_open:
                        # 处理主菜单项点击
                        for item in self.menu_items:
                            if item['rect'].collidepoint(mouse_pos):
                                if item['action'] == 'new_game':
                                    self.new_game()
                                elif item['action'] == 'size_menu':
                                    self.size_menu_open = not self.size_menu_open
                                    self.side_menu_open = False
                                    self.difficulty_menu_open = False
                                    self.menu_interaction_blocked = True
                                elif item['action'] == 'difficulty_menu':  # 处理难度选择
                                    self.difficulty_menu_open = not self.difficulty_menu_open
                                    self.size_menu_open = False
                                    self.side_menu_open = False
                                    self.menu_interaction_blocked = True
                                elif item['action'] == 'choose_side':  # 处理棋子选择
                                    self.side_menu_open = not self.side_menu_open
                                    self.size_menu_open = False
                                    self.difficulty_menu_open = False
                                    self.menu_interaction_blocked = True
                                elif item['action'] == 'return_home':
                                    self.return_to_menu = True
                                    return
                                elif item['action'] == 'exit':
                                    pygame.quit()
                                    sys.exit()

                        # 处理棋盘尺寸选择
                        if self.size_menu_open:
                            for option in self.size_options:
                                if option['rect'].collidepoint(mouse_pos):
                                    self.board_size = option['size']
                                    self.new_game()
                                    self.size_menu_open = False
                                    self.menu_interaction_blocked = True

                        # 处理棋子选择
                        if self.side_menu_open:
                            for option in self.side_options:
                                if option['rect'].collidepoint(mouse_pos):
                                    if option['side'] != self.player_side:
                                        self.player_side = option['side']
                                        self.ai_side = 'BLACK' if self.player_side == 'WHITE' else 'WHITE'
                                        self.new_game()
                                    self.side_menu_open = False
                                    self.game_menu_open = False  # 关闭主菜单
                                    self.menu_interaction_blocked = True

                        # 处理难度选择
                        if self.difficulty_menu_open:
                            for option in self.difficulty_options:
                                if option['rect'] is not None and option['rect'].collidepoint(mouse_pos):
                                    self.difficulty = option['level']
                                    self.difficulty_menu_open = False
                                    self.game_menu_open = False  # 关闭主菜单
                                    self.menu_interaction_blocked = True

                    # 处理按钮点击 - 只有在游戏未结束且菜单未展开时才允许
                    if not self.game_menu_open and not self.menu_interaction_blocked and not self.game_over:
                        for button in self.buttons:
                            if button['rect'].collidepoint(mouse_pos):
                                if button['action'] == 'withdraw':
                                    self.withdraw()
                                elif button['action'] == 'admit_defeat':
                                    self.admit_defeat()
                                elif button['action'] == 'pass_turn':
                                    self.pass_turn()

                    # 处理棋盘点击 - 只有在允许棋盘交互且轮到玩家时才处理
                    if self.is_board_interaction_allowed() and self.current_player == self.player_side:
                        board_rect = pygame.Rect(50, 50, self.board_width - 100, self.board_width - 100)
                        if board_rect.collidepoint(mouse_pos):
                            cell_size = min(board_rect.width, board_rect.height) / (self.board_size - 1)
                            col = round((mouse_pos[0] - board_rect.left) / cell_size)
                            row = round((mouse_pos[1] - board_rect.top) / cell_size)
                            self.place_stone(int(row), int(col), is_ai=False)

            self.draw()
            clock.tick(30)


# 启动游戏
if __name__ == "__main__":
    while True:
        # 显示开始菜单
        start_menu = StartMenu()
        mode = start_menu.run()  # 获取用户选择的模式

        if mode:  # 如果用户选择了模式（而非关闭窗口）
            game = GoGame()  # 传入模式参数
            game.run()

            # 检查是否需要返回首页
            if game.return_to_menu:
                continue  # 重新显示开始菜单
            else:
                break  # 退出游戏
        else:
            break  # 退出游戏